<template>
  <div class="recycle-activity">
    <!-- 回收站点地图 -->
    <el-row style="margin-bottom: 20px;">
      <el-col :span="24">
        <el-card>
          <div slot="header" class="card-header">
            <span>附近回收站点</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshStations">
              刷新站点
            </el-button>
          </div>
          <div class="map-container">
            <div v-if="stations.length === 0" class="map-placeholder">
              <i class="el-icon-location" style="font-size: 48px; color: #67C23A;"></i>
              <p>暂无回收站点</p>
              <p style="font-size: 12px; color: #909399;">请联系管理员添加回收站点</p>
            </div>
            <div v-else class="stations-list">
              <div v-for="station in stations" :key="station.id" class="station-item">
                <div class="station-info">
                  <div class="station-name">{{ station.name }}</div>
                  <div class="station-address">{{ station.address }}</div>
                  <div class="station-types">
                    <el-tag v-for="type in station.types" :key="type" size="mini" style="margin-right: 5px;">
                      {{ type }}
                    </el-tag>
                  </div>
                  <div class="station-time">{{ station.openTime }}</div>
                </div>
                <div class="station-actions">
                  <el-button size="mini" type="primary" @click="selectStation(station)">
                    选择此站点
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 回收记录 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>我的回收记录</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="getRecycleRecords">
              刷新记录
            </el-button>
          </div>
          <div class="record-list">
            <div v-for="record in recycleRecords" :key="record.id" class="record-item">
              <div class="record-icon">
                <i :class="getRecycleIcon(record.type)" :style="{color: getRecycleColor(record.type)}"></i>
              </div>
              <div class="record-info">
                <div class="record-title">
                  回收{{ record.type }} {{ record.quantity }}{{ record.unit }}
                </div>
                <div class="record-station">{{ record.station }}</div>
                <div class="record-time">{{ formatDate(record.date) }}</div>
              </div>
              <div class="record-score">
                +{{ record.points }}分
              </div>
            </div>
          </div>
          <div class="record-empty" v-if="recycleRecords.length === 0">
            <el-empty description="暂无回收记录" :image-size="80"></el-empty>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>快速回收</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="showRecycleDialog">
              详细回收
            </el-button>
          </div>
          <div class="quick-recycle">
            <el-row :gutter="10">
              <el-col :span="12" v-for="item in recycleTypes" :key="item.type">
                <div class="recycle-type-card" @click="startRecycle(item)">
                  <div class="type-icon">
                    <i :class="item.icon" :style="{color: item.color}"></i>
                  </div>
                  <div class="type-name">{{ item.name }}</div>
                  <div class="type-score">{{ item.score }}分/{{ item.unit }}</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 回收统计 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <div slot="header">
            <span>回收统计</span>
          </div>
          <el-row :gutter="20" class="stats-row">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ totalRecycleCount }}</div>
                <div class="stat-label">回收次数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ totalRecycleScore }}</div>
                <div class="stat-label">获得积分</div>
              </div>
            </el-col>
<!--            <el-col :span="6">-->
<!--              <div class="stat-item">-->
<!--                <div class="stat-value">{{ totalRecycleWeight }}</div>-->
<!--                <div class="stat-label">回收重量(kg)</div>-->
<!--              </div>-->
<!--            </el-col>-->
<!--            <el-col :span="6">-->
<!--              <div class="stat-item">-->
<!--                <div class="stat-value">{{ carbonReduction }}</div>-->
<!--                <div class="stat-label">减排CO₂(kg)</div>-->
<!--              </div>-->
<!--            </el-col>-->
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细回收对话框 -->
    <el-dialog title="详细回收" :visible.sync="recycleDialogVisible" width="500px">
      <el-form :model="recycleForm" :rules="recycleRules" ref="recycleForm" label-width="100px">
        <el-form-item label="回收站点" prop="stationId">
          <el-select v-model="recycleForm.stationId" placeholder="请选择回收站点" style="width: 100%">
            <el-option
              v-for="station in stations"
              :key="station.id"
              :label="station.name"
              :value="station.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回收类型" prop="type">
          <el-select v-model="recycleForm.type" placeholder="请选择回收类型" style="width: 100%">
            <el-option
              v-for="item in recycleTypes"
              :key="item.type"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回收数量" prop="quantity">
          <el-input-number
            v-model="recycleForm.quantity"
            :min="0.1"
            :precision="2"
            style="width: 100%">
          </el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="recycleForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="recycleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRecycleForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRecycleRecords, submitRecycle, getRecycleStations } from '@/api/credit/prosocial'

export default {
  name: "RecycleActivity",
  data() {
    return {
      recycleRecords: [],
      stations: [],
      recycleTypes: [
        {
          type: 'plastic',
          name: '塑料瓶',
          icon: 'el-icon-bottle',
          color: '#409EFF',
          score: 2,
          unit: '个'
        },
        {
          type: 'paper',
          name: '废纸',
          icon: 'el-icon-document',
          color: '#67C23A',
          score: 4,
          unit: 'kg'
        },
        {
          type: 'battery',
          name: '废电池',
          icon: 'el-icon-mobile-phone',
          color: '#E6A23C',
          score: 5,
          unit: '个'
        },
        {
          type: 'electronic',
          name: '电子产品',
          icon: 'el-icon-monitor',
          color: '#F56C6C',
          score: 10,
          unit: '个'
        }
      ],
      totalRecycleCount: 0,
      totalRecycleScore: 0,
      totalRecycleWeight: 0,
      carbonReduction: 0,
      loading: false,
      recycleDialogVisible: false,
      recycleForm: {
        stationId: 1,
        type: '',
        quantity: 1.0,
        remark: ''
      },
      recycleRules: {
        stationId: [
          { required: true, message: '请选择回收站点', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择回收类型', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入回收数量', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getRecycleRecords();
    this.getRecycleStations();
  },
  methods: {
    /** 获取回收记录 */
    getRecycleRecords() {
      this.loading = true;
      getRecycleRecords().then(response => {
        if (response.code === 200) {
          this.recycleRecords = response.data || [];
          this.calculateStats();
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 获取回收站点 */
    getRecycleStations() {
      getRecycleStations().then(response => {
        if (response.code === 200) {
          this.stations = response.data || [];
        }
      });
    },

    /** 计算统计数据 */
    calculateStats() {
      this.totalRecycleCount = this.recycleRecords.length;
      this.totalRecycleScore = this.recycleRecords.reduce((sum, record) => sum + (record.points || 0), 0);
      this.totalRecycleWeight = this.recycleRecords.reduce((sum, record) => {
        const weight = parseFloat(record.weight) || 0;
        return sum + weight;
      }, 0);
      this.carbonReduction = parseFloat((this.totalRecycleWeight * 0.5).toFixed(2));
    },

    /** 获取回收类型图标 */
    getRecycleIcon(type) {
      const iconMap = {
        '塑料瓶': 'el-icon-bottle',
        '废纸': 'el-icon-document',
        '废电池': 'el-icon-mobile-phone',
        '电子产品': 'el-icon-monitor'
      };
      return iconMap[type] || 'el-icon-goods';
    },

    /** 获取回收类型颜色 */
    getRecycleColor(type) {
      const colorMap = {
        '塑料瓶': '#409EFF',
        '废纸': '#67C23A',
        '废电池': '#E6A23C',
        '电子产品': '#F56C6C'
      };
      return colorMap[type] || '#909399';
    },

    /** 刷新站点 */
    refreshStations() {
      this.getRecycleStations();
      this.$message.success('站点信息已刷新');
    },

    /** 选择站点 */
    selectStation(station) {
      this.recycleForm.stationId = station.id;
      console.log(this.recycleForm.stationId);
      this.$message.success(`已选择站点：${station.name}`);
    },

    /** 显示回收对话框 */
    showRecycleDialog() {
      this.recycleDialogVisible = true;
      this.recycleForm = {
        stationId: null,
        type: '',
        quantity: 1.0,
        remark: ''
      };
    },

    /** 提交回收表单 */
    submitRecycleForm() {
      this.$refs.recycleForm.validate((valid) => {
        if (valid) {
          console.log("选择站点{}", this.recycleForm.stationId);
          const recycleData = {
            stationId: this.recycleForm.stationId,
            type: this.recycleForm.type,
            quantity: this.recycleForm.quantity,
            remark: this.recycleForm.remark
          };
          this.submitRecycle(recycleData);
        }
      });
    },

    /** 开始回收 */
    startRecycle(item) {
      if (this.stations.length === 0) {
        this.$message.warning('暂无可用的回收站点，请联系管理员');
        return;
      }

      this.$confirm(`确认回收${item.name}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const recycleData = {
          // 纯纯弱智，默认第一个站点？？？谁教你的
          // stationId: this.stations[0].id, // 默认选择第一个站点
          stationId: this.recycleForm.stationId,
          type: item.name,
          quantity: 1.0,
          remark: '快速回收'
        };
        this.submitRecycle(recycleData);
      });
    },

    /** 提交回收 */
    submitRecycle(recycleData) {
      submitRecycle(recycleData).then(response => {
        if (response.code === 200) {
          this.$message.success(`回收成功，获得${response.data.points}积分`);
          this.recycleDialogVisible = false;
          // 刷新回收记录
          this.getRecycleRecords();
        } else {
          this.$message.error(response.msg || "回收失败");
        }
      }).catch(() => {
        this.$message.error("回收失败，请稍后重试");
      });
    },

    /** 格式化日期 */
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    }
  }
};
</script>

<style scoped>
.map-container {
  min-height: 200px;
  max-height: 400px;
  overflow-y: auto;
}

.map-placeholder {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 4px;
  color: #909399;
}

.stations-list {
  padding: 10px 0;
}

.station-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  margin-bottom: 10px;
  background-color: #fafafa;
}

.station-item:hover {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.station-info {
  flex: 1;
}

.station-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.station-address {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.station-types {
  margin-bottom: 5px;
}

.station-time {
  font-size: 12px;
  color: #909399;
}

.station-actions {
  margin-left: 15px;
}

.record-list {
  max-height: 300px;
  overflow-y: auto;
}

.record-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #EBEEF5;
}

.record-item:last-child {
  border-bottom: none;
}

.record-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-right: 15px;
}

.record-info {
  flex: 1;
}

.record-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
}

.record-station {
  font-size: 12px;
  color: #606266;
  margin-bottom: 3px;
}

.record-time {
  font-size: 12px;
  color: #909399;
}

.record-score {
  font-size: 14px;
  color: #67C23A;
  font-weight: bold;
}

.quick-recycle {
  padding: 10px 0;
}

.recycle-type-card {
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 10px;
}

.recycle-type-card:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.type-icon {
  font-size: 28px;
  margin-bottom: 10px;
}

.type-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
}

.type-score {
  font-size: 12px;
  color: #67C23A;
}

.stats-row {
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  background-color: #f8f9fa;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.record-empty {
  padding: 40px 0;
}
</style>
